package com.netease.neliveplayer.playerkit.videoLoader;

import android.util.Log;

import com.netease.neliveplayer.playerkit.sdk.LivePlayer;
import com.netease.neliveplayer.proxy.gslb.NEGslbResultListener;
import com.netease.neliveplayer.proxy.gslb.NEGslbServerModel;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/*
* glsb回调
* */
public class GslbResultListener implements NEGslbResultListener {
    //原始url
    String originalUrl;
    //预加载起始位置
    private int from;
    private static int call = 0;
    private static int finish = 0;
    ArrayList<VideoLoader.VideoInfo> mVideoList;
    private boolean group;
    private boolean play;
    private LivePlayer mPlayer;
    GslbResultListener(ArrayList<VideoLoader.VideoInfo> videoList, String url, int idx){
        originalUrl = url;
        from = idx;
        mVideoList = videoList;
        call++;
        group = true;
    }

    public GslbResultListener(LivePlayer player, String url) {
        mPlayer = player;
        originalUrl = url;
        group = false;
    }

    public GslbResultListener(LivePlayer player, String url, boolean needPlay) {
        mPlayer = player;
        originalUrl = url;
        group = false;
        play = needPlay;
    }

    @Override
    public synchronized void onResult(Object o, List<NEGslbServerModel> list) {
        if (list.size() > 0) {
            if(group)
                finish++;
            VideoLoaderImpl.getInstance().glsbResultAdd(originalUrl, o, list.get(0));
        }
        if (group) {
            if (call == finish) {
                call = 0;
                finish = 0;

                if (from < 0) {
                    from = 0;
                }
                //对前六个进行预加载
                int second = Math.max(0, Math.min(from + 1, mVideoList.size() - 1));
                int third = Math.max(0, Math.min(from + 2, mVideoList.size() - 1));
                int fourth = Math.max(0, Math.min(from + 3, mVideoList.size() - 1));
                int fifth = Math.max(0, Math.min(from + 4, mVideoList.size() - 1));
                int sixth = Math.max(0, Math.min(from + 5, mVideoList.size() - 1));
                ArrayList<ArrayList<String>> urlList = new ArrayList<>(Arrays.asList(mVideoList.get(from).url,
                        mVideoList.get(second).url, mVideoList.get(third).url, mVideoList.get(fourth).url, mVideoList.get(fifth).url, mVideoList.get(sixth).url));
                VideoLoaderImpl.getInstance().setLivePlayerURLList(urlList);
                VideoLoaderImpl.getInstance().stopAllRefresher();
                VideoLoaderImpl.getInstance().startAllRefresher();
            }
        }else if(mPlayer != null){
            mPlayer.switchWithGslbResult(o, list.get(0));
            if(play){
                play = false;
                mPlayer.startWithoutInit();
            }
        }
    }
}
